package com.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.common.bean.execption.CheckedException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据校验
 */
public class Assert {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws CheckedException  校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws CheckedException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getMessage()).append("<br>");
            }
            throw new CheckedException(msg.toString());
        }
    }

    public static void isBlank(Object object, String message, String ...param) {
        if (object == null) {
            throw new CheckedException(StrUtil.format(message, param));
        }
        if(object instanceof String && StrUtil.isBlank(object.toString())) {
            throw new CheckedException(message);
        }
        if(object instanceof Map && CollUtil.isEmpty((Map) object)) {
            throw new CheckedException(message);
        }
        if(object instanceof List && CollUtil.isEmpty((List) object)) {
            throw new CheckedException(message);
        }
        if(object instanceof Set && CollUtil.isEmpty((Set) object)) {
            throw new CheckedException(message);
        }
    }
}
